<template>
  <view class="settings-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="navigateBack">
        <image class="back-icon" :src="getImageUrl('/static/Images/user/Fanhui.png')" mode="aspectFit"></image>
      </view>
      <view class="title">设置</view>
    </view>
    
    <!-- 个人资料区域 -->
    <view class="section-container">
      <view class="section-title">个人资料</view>
      
      <!-- 头像 -->
      <view class="setting-item" @click="handleAvatarClick">
        <view class="item-label">头像</view>
        <view class="item-content avatar-content">
          <image class="avatar-image" :src="userInfo.avatar" mode="aspectFill"></image>
          <image class="arrow-icon" :src="getImageUrl('/static/Images/team/Qianjin.png')" mode="aspectFit"></image>
        </view>
      </view>
      
      <!-- 昵称 -->
      <view class="setting-item" @click="handleNicknameClick">
        <view class="item-label">昵称</view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.nickname }}</text>
          <image class="arrow-icon" :src="getImageUrl('/static/Images/team/Qianjin.png')" mode="aspectFit"></image>
        </view>
      </view>
      
      <!-- UID -->
      <view class="setting-item">
        <view class="item-label">UID</view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.uid }}</text>
          <view class="copy-btn" @click="copyToClipboard(userInfo.uid)">
            <image class="copy-icon" :src="getImageUrl('/static/Images/team/Fuzhi.png')" mode="aspectFit"></image>
          </view>
        </view>
      </view>
      
      <!-- 密钥 -->
      <view class="setting-item">
        <view class="item-label">密钥</view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.secretKey }}</text>
          <view class="copy-btn" @click="copyToClipboard(userInfo.secretKey)">
            <image class="copy-icon" :src="getImageUrl('/static/Images/team/Fuzhi.png')" mode="aspectFit"></image>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 修改手机号 -->
    <view class="section-container">
      <view class="section-title">修改手机号</view>
      <view class="setting-item" @click="handlePhoneClick">
        <view class="item-label">手机号</view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.phone }}</text>
          <image class="arrow-icon" :src="getImageUrl('/static/Images/team/Qianjin.png')" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    
    <!-- 第三方绑定 -->
    <view class="section-container">
      <view class="section-title">第三方绑定</view>
      
      <!-- 微信 -->
      <view class="setting-item" @click="handleWechatClick">
        <view class="item-label">
          <image class="platform-icon" :src="getImageUrl('/static/Images/pay/Weixinhei.png')" mode="aspectFit"></image>
          <text>微信</text>
        </view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.wechatBound ? '已绑定' : '未绑定' }}</text>
          <image class="arrow-icon" :src="getImageUrl('/static/Images/team/Qianjin.png')" mode="aspectFit"></image>
        </view>
      </view>
      
      <!-- QQ -->
      <view class="setting-item" @click="handleQQClick">
        <view class="item-label">
          <image class="platform-icon" :src="getImageUrl('/static/Images/pay/Zhifubaohei.png')" mode="aspectFit"></image>
          <text>QQ</text>
        </view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.qqBound ? '已绑定' : '未绑定' }}</text>
          <image class="arrow-icon" :src="getImageUrl('/static/Images/team/Qianjin.png')" mode="aspectFit"></image>
        </view>
      </view>
      
      <!-- 支付宝 -->
      <view class="setting-item" @click="handleAlipayClick">
        <view class="item-label">
          <image class="platform-icon" :src="getImageUrl('/static/Images/wallet/AliPay.png')" mode="aspectFit"></image>
          <text>支付宝</text>
        </view>
        <view class="item-content">
          <text class="item-value">{{ userInfo.alipayBound ? '已绑定' : '未绑定' }}</text>
          <image class="arrow-icon" :src="getImageUrl('/static/Images/team/Qianjin.png')" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    
    <!-- 注销账号 -->
    <view class="action-button danger" @click="handleLogoutAccount">
      注销账号
    </view>
    
    <!-- 退出登录 -->
    <view class="action-button logout" @click="handleSignOut">
      退出登录
    </view>
    
    <!-- 底部安全区域 -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { userApi, indexApi } from '@/utils/api';
import { userStorage } from '@/utils/storage';
import { getImageUrl } from '@/config/api';

// 用户信息
const userInfo = reactive({
  avatar: '/static/Images/touxiang/1.png',
  nickname: '用户昵称',
  uid: '123546854179',
  secretKey: 'PDJDBANDJA123546854',
  phone: '15762459634',
  wechatBound: true,
  qqBound: false,
  alipayBound: true
});

// 清理头像 URL（去除可能的反引号和首尾空白）
const normalizeUrl = (url) => {
  if (typeof url !== 'string') return '';
  return url.replace(/^\s*`|`\s*$/g, '').trim();
};

// 获取用户信息并渲染到设置页
const fetchUserInfo = async () => {
  try {
    if (!userStorage.isLoggedIn()) return;
    const response = await userApi.getUserInfo();
    const data = (response && (response.data?.data ?? response.data ?? response)) || {};

    // 昵称：优先 nick_name 其次 nickname/name
    userInfo.nickname = data.nick_name || data.nickname || data.name || userInfo.nickname;
    // 头像：清理反引号并设置默认
    const avatarUrl = normalizeUrl(data.avatar);
    userInfo.avatar = avatarUrl || '/static/Images/touxiang/1.png';
    // UID：优先 id 或 uid
    userInfo.uid = String(data.id ?? data.uid ?? userInfo.uid);
    // 手机号：优先 mobile 其次 phone
    userInfo.phone = data.mobile ?? data.phone ?? userInfo.phone;
    // 密钥：取后端 pwd 字段
    if (typeof data.pwd !== 'undefined') {
      userInfo.secretKey = data.pwd;
    }
  } catch (err) {
    console.error('获取设置页用户信息失败:', err);
  }
};

// 页面显示时拉取最新用户信息
onShow(() => {
  fetchUserInfo();
});

// 返回用户主页
const navigateBack = () => {
  uni.navigateTo({
    url: '/pages/users/index'
  });
};

// 复制到剪贴板
const copyToClipboard = (text) => {
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      });
    }
  });
};

// 处理头像点击
const handleAvatarClick = () => {
  uni.showActionSheet({
    itemList: ['拍照', '从相册选择'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 拍照
        uni.chooseImage({
          count: 1,
          sourceType: ['camera'],
          success: async (res) => {
            const avatarPath = res.tempFilePaths[0];
            await updateAvatar(avatarPath);
          }
        });
      } else if (res.tapIndex === 1) {
        // 从相册选择
        uni.chooseImage({
          count: 1,
          sourceType: ['album'],
          success: async (res) => {
            const avatarPath = res.tempFilePaths[0];
            await updateAvatar(avatarPath);
          }
        });
      }
    }
  });
};

// 更新头像到后端
const updateAvatar = async (avatarPath) => {
  try {
    console.log('开始更新头像流程，本地图片路径:', avatarPath);
    uni.showLoading({ title: '保存中...' });

    // 本地预览
    userInfo.avatar = avatarPath;
    console.log('设置本地预览完成');

    // 1) 先上传文件，拿到 save_path
    console.log('开始上传图片到服务器...');
    const savePath = await indexApi.uploadFile(avatarPath);
    console.log('上传成功，获得 save_path:', savePath);

    // 2) 再提交修改用户信息，字段为 avatar（取 save_path）
    console.log('开始更新用户头像信息...');
    const updateResult = await userApi.changeUserInfo({ avatar: savePath });
    console.log('头像信息更新成功:', updateResult);

    // 替换为线上URL，确保后续显示的一致性
    userInfo.avatar = savePath;

    uni.hideLoading();
    uni.showToast({ title: '头像保存成功', icon: 'success' });
    console.log('头像更新流程完成');
  } catch (error) {
    uni.hideLoading();
    console.error('头像更新失败，错误详情:', error);
    console.error('错误堆栈:', error.stack);
    
    // 回滚到原头像
    await fetchUserInfo();
    
    let errorMessage = '头像保存失败';
    if (error.message) {
      errorMessage = error.message;
    }
    
    uni.showToast({ 
      title: errorMessage, 
      icon: 'error',
      duration: 3000
    });
    
    // 同时显示详细错误信息的模态框
    uni.showModal({
      title: '头像更新失败',
      content: `错误原因: ${errorMessage}\n\n请检查网络连接或联系客服`,
      showCancel: false
    });
  }
};

// 处理昵称点击
const handleNicknameClick = () => {
  uni.navigateTo({
    url: '/pages/users/nickname'
  });
};

// 处理手机号点击
const handlePhoneClick = () => {
  uni.navigateTo({
    url: '/pages/users/phone'
  });
};

// 处理微信点击
const handleWechatClick = () => {
  if (userInfo.wechatBound) {
    uni.showModal({
      title: '提示',
      content: '是否解除微信绑定？',
      success: (res) => {
        if (res.confirm) {
          userInfo.wechatBound = false;
          uni.showToast({
            title: '已解除绑定',
            icon: 'success'
          });
        }
      }
    });
  } else {
    // 执行微信绑定
    uni.showToast({
      title: '正在绑定微信...',
      icon: 'loading',
      duration: 2000
    });
    setTimeout(() => {
      userInfo.wechatBound = true;
      uni.showToast({
        title: '绑定成功',
        icon: 'success'
      });
    }, 2000);
  }
};

// 处理QQ点击
const handleQQClick = () => {
  if (userInfo.qqBound) {
    uni.showModal({
      title: '提示',
      content: '是否解除QQ绑定？',
      success: (res) => {
        if (res.confirm) {
          userInfo.qqBound = false;
          uni.showToast({
            title: '已解除绑定',
            icon: 'success'
          });
        }
      }
    });
  } else {
    // 执行QQ绑定
    uni.showToast({
      title: '正在绑定QQ...',
      icon: 'loading',
      duration: 2000
    });
    setTimeout(() => {
      userInfo.qqBound = true;
      uni.showToast({
        title: '绑定成功',
        icon: 'success'
      });
    }, 2000);
  }
};

// 处理支付宝点击
const handleAlipayClick = () => {
  if (userInfo.alipayBound) {
    uni.showModal({
      title: '提示',
      content: '是否解除支付宝绑定？',
      success: (res) => {
        if (res.confirm) {
          userInfo.alipayBound = false;
          uni.showToast({
            title: '已解除绑定',
            icon: 'success'
          });
        }
      }
    });
  } else {
    // 执行支付宝绑定
    uni.showToast({
      title: '正在绑定支付宝...',
      icon: 'loading',
      duration: 2000
    });
    setTimeout(() => {
      userInfo.alipayBound = true;
      uni.showToast({
        title: '绑定成功',
        icon: 'success'
      });
    }, 2000);
  }
};

// 处理注销账号
const handleLogoutAccount = () => {
  uni.navigateTo({
    url: '/pages/login/logout'
  });
};

// 处理退出登录
const handleSignOut = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '退出中...' });
          await userApi.logout();
          userStorage.removeToken();
          userStorage.removeUserInfo();
          uni.hideLoading();
          uni.showToast({ title: '已退出登录', icon: 'success', duration: 1500 });
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/login/login' });
          }, 1500);
        } catch (error) {
          uni.hideLoading();
          console.error('退出登录失败:', error);
          userStorage.removeToken();
          userStorage.removeUserInfo();
          uni.showToast({ title: '已退出登录', icon: 'success', duration: 1500 });
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/login/login' });
          }, 1500);
        }
      }
    }
  });
};
</script>

<style lang="scss">
.settings-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

/* 导航栏 */
.nav-bar {
  position: relative;
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #ffffff;
  padding-top: 88rpx;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.back-icon {
  height: 54rpx;
  margin-left: -30rpx;
}

.title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

/* 区域容器 */
.section-container {
  margin: 20rpx 0;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.section-title {
  font-size: 28rpx;
  color: #999;
  padding: 20rpx 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

/* 设置项 */
.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.setting-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 30rpx;
  color: #333;
  display: flex;
  align-items: center;
}

.platform-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.item-content {
  display: flex;
  align-items: center;
}

.item-value {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.arrow-icon {
  width: 30rpx;
  height: 30rpx;
}

/* 头像 */
.avatar-content {
  display: flex;
  align-items: center;
}

.avatar-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 10rpx;
}

/* 复制按钮 */
.copy-btn {
  padding: 10rpx;
}

.copy-icon {
  width: 30rpx;
  height: 30rpx;
}

/* 操作按钮 */
.action-button {
  margin: 30rpx;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: 500;
}

.danger {
  background-color: #fff;
  color: #FF3037;
  border: 2rpx solid #FF3037;
}

.logout {
  background-color: #FF3037;
  color: #fff;
}

.safe-area-bottom {
  height: env(safe-area-inset-bottom);
}
</style>